package com.jiantong.version.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import io.terminus.common.utils.JsonMapper;
import lombok.Data;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

/**
 * Created by mz on 25/8/17.
 *
 */
@Data
public class Dictionary implements Serializable{

    private static final long serialVersionUID = -2134258012887376557L;

    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();

    /**
     * 主键
     */
    private Long id;

    /**
     * 码名类型
     */
    private Integer type;

    /**
     * 码名类型名
     */
    private String typeName;

    /**
     * 码名json
     */
    @JsonIgnore
    private String codeNameJson;

    /**
     * 码名map
     */
    private Map<Integer , String> codeNameMap;


    public void setCodeNameJson(String codeNameJson){

        this.codeNameJson = codeNameJson;

        if(Strings.isNullOrEmpty(codeNameJson)){
            this.codeNameMap = Maps.newHashMap();
        }else {
            try {
                this.codeNameMap = objectMapper.readValue(codeNameJson, new TypeReference<Map<Integer,String>>() {});
            } catch (IOException e) {
                //this is fuck exception
            }
        }
    }


    public void setCodeNameMap(Map<Integer,String> codeNameMap){
        this.codeNameMap = codeNameMap;

        if(codeNameMap == null || codeNameMap.isEmpty()){
            this.codeNameJson = null;
        }else {
            try {
                this.codeNameJson = objectMapper.writeValueAsString(codeNameMap);
            } catch (JsonProcessingException e) {
                //this is fuck exception
            }
        }
    }


}
